from fastapi import APIRouter, Body, Query
from fastapiApp.controllers.user_control import *
from fastapiApp.schemas.base_scheams import Fail, Success, SuccessExtra
from fastapiApp.schemas.user_schemas import *
from fastapiApp.models.admin import User_Mo
import secrets

router = APIRouter()

@router.post("/access_token", summary="获取token")
async def login_access_token(credentials: CredentialsSchema):
    user: User_Mo = await user_controller.authenticate(credentials)
    await user_controller.update_last_login(user.id)

    data = JWTOut(
        access_token=secrets.token_hex(32),
        username=user.username,
    )

    creat_GL_DependAuth(data.username,data.access_token)
    return Success(msg="success",data=data.__dict__)

@router.get("/get_list", summary="查看用户列表")
async def list_user(
    page: int = Query(1, description="页码"),
    page_size: int = Query(10, description="每页数量"),
    username: str = Query("", description="用户名称，用于搜索"),
    email: str = Query("", description="邮箱地址"),
    dept_id: int = Query(None, description="部门ID")
):
    total,data = await user_controller.list(page=page, page_size=page_size, username=username,email=email,dept_id=dept_id)
    return SuccessExtra(data=data, total=total, page=page, page_size=page_size)

@router.get("/get_info", summary="查看用户")
async def get_user(id: int = Query(..., description="用户ID")):
    user_obj = await user_controller.model.get(id=id)
    data = await user_obj.to_dict()
    return Success(data=data)

@router.post("/create", summary="创建用户")
async def create_user(obj_in: UserCreate):
    await user_controller.is_exist(obj_in = obj_in)
    await user_controller.model.create(** obj_in.model_dump())
    return Success(msg="Created Successfully")

@router.post("/update", summary="更新用户")
async def update_user(obj_in: UserUpdate):
    await user_controller.update_user(obj_in=obj_in)
    return Success(msg=f"Update Successfully By ID = {obj_in.id}")


@router.delete("/delete", summary="删除用户")
async def delete_user(id: int = Query(..., description="用户ID")):
    user = await user_controller.model.get_or_none(id = id)
    if user:
        await user.delete()
        return Success(msg=f"Deleted Success By ID = {id}")
    else:
        return Fail(msg=f"ID {id} 不存在")

@router.post("/reset_password", summary="重置密码")
async def reset_password(user_id: int = Body(..., description="用户ID", embed=True)):
    await user_controller.reset_password(user_id)
    return Success(msg="密码已重置为123456")
